import express from 'express';
import Core from '@alicloud/pop-core'; // 阿里发送短信sdk
import CONFIG from '../../../config/config.config'
import { verifySession } from '../../common/verify'; // 验证码集合

const router = express.Router();
const minLevel = 0; // 允许调用接口的最低等级

router.post('/', async function (Request, Response, next) {
  // User.Modal.sync();
  // 权限校验
  // await checkPermission(Request, Response, minLevel)

  let param = Request.body
  let verify = "" // 验证码
  for (var i = 0; i < 6; i++) {
    // 生成验证码
    verify += Math.floor(Math.random() * 10)
  }
  let client = new Core({
    accessKeyId: CONFIG.aliAccessKeyID,
    accessKeySecret: CONFIG.aliAccessKeySecret,
    endpoint: 'https://dysmsapi.aliyuncs.com',
    apiVersion: '2017-05-25'
  });
  let smsParam = {
    RegionId: "cn-hangzhou",
    PhoneNumbers: param.mobile,
    SignName: "杂货铺",
    TemplateCode: CONFIG.aliTemplateCode,
    TemplateParam: `{code: ${verify}}`
  }
  // 发送验证码
  client.request('SendSms', smsParam, 'POST').then(result => {
  verifySession[param.mobile] = `{"verify":"${verify}", "expiredAt":${new Date().valueOf() + 1000 * 60 * 5}}` //存储session
    Response.json({
      data: "",
      message: "success"
    });
  }, (ex) => {
    if (ex.data) {
      Response.status(300).send({ message: ex.data.Message || '未知错误，短信发送失败' });
    }
  })
  // !!!!!!调试!!!!!!
  // console.log(verify)
  // verifySession[param.mobile] = `{"verify":"${verify}", "expiredAt":${new Date().valueOf() + 1000 * 60 * 5}}` //存储session
  // !!!!!!调试!!!!!!

  Response.json({
    data: "",
    message: "success"
  });
});
module.exports = router;